<!-- 新建实物奖品 -->
<template>
  <a-drawer v-model:visible="vdata.visible" :maskClosable="false" width="40%">
    <template #title>
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <span v-if="vdata.isAdd">新增福分奖品</span>
        <span v-else>{{ vdata.disabled ? '追加' : '修改' }}福分奖品</span>
        <a-button :disabled="vdata.disabled" @click="onSaveDraft">保存草稿</a-button>
      </div>
    </template>
    <Step :current-step="vdata.currentStep" :steps="stepsConfig" />
    <a-form
      v-if="vdata.currentStep==0"
      ref="stepForm0Ref"
      :model="vdata.baseObject"
      layout="vertical"
      labelAlign="left"
      :rules="vdata.rules"
      :colon="false"
      :wrapper-col="{ span: 24 }"
      style="margin-top: 30px; margin-left: 20px"
    >
      <a-row type="flex" justify="space-between">
        <a-col :span="11">
          <a-form-item label="机构" name="agentNo">
            <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.baseObject['agentNo']" :disabled="vdata.disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="福分名称" name="scoreName">
            <a-input v-model:value="vdata.baseObject['scoreName']" placeholder="福分名称" :disabled="vdata.disabled" :maxlength="16" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="福分面值" name="scoreValue">
            <a-input-number
              v-model:value="vdata.baseObject['scoreValue']"
              placeholder="福分面值"
              :disabled="vdata.disabled"
              style="width: 100%;"
              :precision="0"
              min="0"
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="福分数量" name="scoreNum">
            <a-input-number
              v-model:value="vdata.baseObject['scoreNum']"
              :min="vdata.minScoreNum"
              placeholder="当数量为0时，表示无限制/安慰奖"
              :precision="0"
              :disabled="vdata.disabled"
              style="width: 100%;"
            />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="11">
          <a-form-item label="预算金额" name="ScoreAmount" >
            <a-input-number v-model:value="vdata.baseObject['ScoreAmount']" :precision="2" style="width: 100%" min="0" disabled placeholder="0" />
          </a-form-item>
        </a-col> -->
        <a-col :span="11">
          <a-form-item label="福分过期规则类型" name="overType">
            <a-select v-model:value="vdata.baseObject['overType']" placeholder="请选择福分过期规则类型" :disabled="vdata.disabled">
              <a-select-option :value="0">n天后过期</a-select-option>
              <a-select-option :value="1">指定过期时间</a-select-option>
              <a-select-option :value="2">次季度首月月底失效</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.baseObject['overType'] === 0" :span="11">
          <a-form-item label="有效天数" name="overDays">
            <a-input-number
              v-model:value="vdata.baseObject['overDays']"
              :disabled="vdata.disabled"
              :precision="0"
              min="0"
              placeholder="有效天数"
              style="width: 100%;"
            />
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.baseObject['overType'] === 1" :span="11">
          <a-form-item label="过期时间" name="overTime">
            <a-date-picker v-model:value="vdata.baseObject['overTime']" :disabled="vdata.disabled" valueFormat="YYYY-MM-DD" :disabled-date="(current)=>current && current < dayjs().endOf('day')" style="width: 100%;" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" name="remark">
            <a-textarea v-model:value="vdata.baseObject['remark']" :disabled="vdata.disabled" :rows="3" placeholder="请输入备注" />
            <span class="gz-tip-text">换行符：\n</span>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    
    <Setting
      v-if="vdata.currentStep==1"
      ref="stepForm1Ref"
      :awardSettingId="awardSettingId"
      :disabled="vdata.disabled"
      :isDisabled="vdata.disabled ||vdata.isDisabled"
      :isDetail="vdata.isDetail"
      @sendData="handleChildrenData"
    />
    <MerchantFrom
      v-if="vdata.currentStep == 2"
      ref="stepForm2Ref"
      :awardId="vdata.baseObject.couponId"
      :awardType="awardType"
      :isDetail="vdata.isDetail"
      :isDisabled="vdata.disabled ||vdata.isDisabled"
    />
    <PersonnelFrom
      v-if="vdata.currentStep == 3"
      ref="stepForm3Ref"
      :awardId="vdata.baseObject.couponId"
      :awardType="awardType"
      :isEmployee="vdata.baseObject.isEmployee"
      :isDisabled="vdata.disabled ||vdata.isDisabled"
      :isDetail="vdata.isDetail"
    />
    <InstitutionFrom
      v-if="vdata.currentStep == 4"
      ref="stepForm4Ref"
      :awardId="vdata.baseObject.couponId"
      :awardType="awardType"
      :isAllocation="vdata.baseObject.isAllocation"
      :agentNo="vdata.baseObject.agentNo"
      :isDisabled="vdata.disabled || vdata.isDisabled"
      :isDetail="vdata.isDetail"
      :isPush="vdata.disabled"
    />
    <div class="drawer-btn-center">
      <a-button v-if="vdata.currentStep != 0" style="margin-right:8px" @click="onSteps(-1)">
        <step-backward-outlined />
        上一步
      </a-button>
      <a-button v-if="vdata.currentStep != 4" :loading="vdata.btnLoading" style="margin-right:8px" @click="onSteps(1)">
        <step-forward-outlined />
        下一步
      </a-button>
      <a-button
        v-if="vdata.currentStep == 4"
        type="primary"
        :loading="vdata.btnLoading"
        @click="onSave()"
      >
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { $scoreAddOrEdit,$scoreState,$scoreDetailt } from '@/api/awardMange/score/index'
import { reactive, ref, defineExpose, watch, getCurrentInstance } from 'vue'
import{$addStting,$updateStting}from '@/api/awardMange/coupon/index'
import dayjs from 'dayjs'
import Step from '../components/step/index.vue'
import Setting from '../components/setting/index.vue'
import PersonnelFrom from '../components/PersonnelFrom/index.vue'
import MerchantFrom from '../components/MerchantFrom/index.vue'
import InstitutionFrom from '../components/InstitutionFrom/index.vue'
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
const { proxy }: any = getCurrentInstance()
const awardType = ref(3)
const stepForm0Ref = ref()
const stepForm1Ref = ref()
const stepForm2Ref = ref()
const stepForm3Ref = ref()
const stepForm4Ref = ref()
const props = defineProps(['callbackFunc'])
const stepsConfig = ref([
  { title: '福分基本信息' },
  { title: '福分配置信息' },
  { title: '可核销商户' },
  { title: '可派发人员' },
  { title: '福分数量配置' }
])
const vdata:any = reactive({
  isAdd: false, // 新增OR修改
  visible: false,
  btnLoading: true,
  baseObject: {},
  minScoreNum: 1,  // 下架状态限制最小数量
  disabled: false,  // 在下架修改时 只允许修改卡券数量 且只能增加不能减少
  rules: {
    scoreName: [{ required: true, message: '福分名称不能为空', trigger: 'blur' },],
    scoreValue: [{ required: true, message: '福分面值不能为空', trigger: 'blur' },],
    scoreNum: [{ required: true, message: '福分数量不能为空', trigger: 'blur' },],
    overType: [{ required: true, message: '过期规则类型不能为空', trigger: 'blur' },],
    overTime: [{ required: true, message: '过期时间不能为空', trigger: 'blur' },],
    overDays: [{ required: true, message: '有效天数不能为空', trigger: 'blur' },],
    agentNo: [{ required: true, message: '机构号不能为空', trigger: 'blur' },],
  },
})
/**
 * 监听卡券张数和面额 自动计算卡券预算
 */
watch([() => vdata.baseObject.scoreValue, () => vdata.baseObject.scoreNum],(newVal, oldVal) =>{
  if(oldVal[0] === undefined && oldVal[1] === undefined) return
  if(vdata.baseObject.scoreValue && vdata.baseObject.scoreNum){
    vdata.baseObject.ScoreAmount = vdata.baseObject.scoreValue * vdata.baseObject.scoreNum
  }
},{ immediate: false })

const couponIdOne = ref()
const couponIdUpdate = ref()
const  baseObjectSetting = ref()

// 接受子组件传递过来的基本信息限制配置的对象 
 function handleChildrenData(childrenObject:any){  
  baseObjectSetting.value = childrenObject.childrenbaseObject
  if(vdata.isAdd){
    vdata.baseObject.couponId = couponIdOne.value
  }else{
    vdata.baseObject.couponId = couponIdUpdate.value
  }
  
 }


/**
 * 切换步骤
 */
function onSteps(step: number) {
  if (step < 0) {
    vdata.currentStep--
  } else {
    if(vdata.isDetail){
      vdata.currentStep++
    }else{
      proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validate().then(() => {
      // 第一步网络请求 奖品信息
      if(vdata.currentStep === 0){
        step0Request(false)
      }else if(vdata.currentStep===1){
          saveStting()
        } else if (vdata.currentStep === 2 || vdata.currentStep === 3) {
          // 第二步 上传可核销商户清单
          if(vdata.currentStep === 3){
          // 调用员工组件暴漏的 handleIsEmployeeChange
          proxy.$refs['stepForm3Ref'].handleIsEmployeeChange()
        
          }
          vdata.currentStep++
        }
        

    }).catch((err)=>{console.log(err)})
    }
    
  }
}


/**
 * 第一步网络请求 卡券信息
 */
function step0Request(isDraft: boolean, showMsg: boolean = false) {
  const uploadObject = JSON.parse(JSON.stringify(vdata.baseObject))
  // 请求方法
  const METHOD = vdata.baseObject.scoreId ? 'PUT' : 'POST'
  // 修改需要传递ID
  if(!vdata.isAdd){
    vdata.baseObject.scoreId = vdata.scoreId
  }
  // 删除冗余数据
  delete uploadObject.awardMchList
  $scoreAddOrEdit(METHOD,uploadObject).then((res)=>{
    if(METHOD === 'POST'){  // 新增时需要拿到卡券id 和awardSettingId
      couponIdOne.value = res.scoreId
    // 新增的时候不会走setting里面的暴漏处来的handleChildrenData这个方法所以拿不到 couponId
      vdata.baseObject.couponId = res.scoreId
      vdata.baseObject.scoreId = res.scoreId
    }
    if(isDraft){
      if(showMsg){
        $infoBox.message.success('保存成功')
        onClose()
      }
      return
    }
    vdata.currentStep++
  })
}


// 通过awardSettingId来查配置的详情
// 第二部网络请求
const awardSettingId = ref()
function saveStting(){  
   const uploadObject =  proxy.$refs['stepForm1Ref'].changehadleSaveStting()
    uploadObject.awardId =  vdata.baseObject.couponId
     uploadObject.awardType = awardType.value      
  if(awardSettingId.value||uploadObject.awardSettingId){
  uploadObject.awardSettingId =  awardSettingId.value?awardSettingId.value:uploadObject.awardSettingId
  $updateStting(uploadObject).then((res) => { 
      $infoBox.message.success('修改成功')
       vdata.currentStep++
  })
  }else{
  $addStting(uploadObject).then((res) => {      
      awardSettingId.value = res
    vdata.currentStep++
  })
  }

}
/**
 * 最后的保存
 */
function onSave() {
  if(vdata.isDetail){
    onClose()
  }else{
    proxy.$refs['stepForm4Ref'].handleIsAllocationChange()
  const  scoreId  = vdata.baseObject.couponId
  const state =  2
  $scoreState( { scoreId, state }).then(() => {
    $infoBox.message.success('保存成功')
    onClose()
  })
  }
   
}


/**
 * 保存草稿
 */
function onSaveDraft(){
  if(vdata.currentStep == 0){ // 在第一步 保存草稿
    // 移除校验结果
    clearFieldValidate()
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validate(['agentNo','goodsName']).then(() => {  // 草稿只验证商品名称
      step0Request(true,true)
    }).catch(()=>{})
  }else if (vdata.currentStep === 1) {
      saveStting()
    // 第二步 保存草稿
    onClose()
  } else if(vdata.currentStep==2) {
    $infoBox.message.success('保存成功')
    onClose()
  }else if(vdata.currentStep==3){
     proxy.$refs['stepForm3Ref'].handleIsEmployeeChange()
      $infoBox.message.success('保存成功')
    onClose()
  }else{
     proxy.$refs['stepForm4Ref'].handleIsAllocationChange()
      $infoBox.message.success('保存成功')
     onClose()

  }
}

function show(record,disabled,isDisabled,isDetail,minScoreNum) {
  console.log(record,disabled,isDisabled,isDetail,minScoreNum,8888888888888888888)
  vdata.isAdd = !record
  vdata.scoreId = record.scoreId
  vdata.btnLoading = false
  vdata.currentStep = 0
  // 重置数据
  vdata.baseObject = {
  }
   awardSettingId.value = null
  vdata.minScoreNum = minScoreNum
  // 如果是详情，则进行禁用只让查看
  vdata.disabled = disabled
  vdata.isDisabled = isDisabled
  // 如果是详情，不想调用接口
  vdata.isDetail = isDetail
  clearFieldValidate()
  if(!vdata.isAdd){ // 修改
    $scoreDetailt({scoreId:vdata.scoreId}).then((res)=>{
        vdata.baseObject = res
          couponIdUpdate.value = res.scoreId
        //  修改的时候拿到settingid去查setting信息
        if(res.awardSetting){
           vdata.baseObject.isAllocation=res.awardSetting?.isAllocation
          vdata.baseObject.isEmployee = res.awardSetting?.isAllocationUser
         awardSettingId.value = res.awardSetting?.awardSettingId
        }
        vdata.visible = true
    })
  }
  vdata.visible = true
}
/**
 * 清除表单字段验证
 */
function clearFieldValidate(){
  if (proxy.$refs['stepForm' + vdata.currentStep + 'Ref'] != undefined) {
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].clearValidate() // 清除验证
  }
}

function onClose() {
  
   if(vdata.isDetail){
    vdata.visible = false
  vdata.baseObject.agentNo = ''
   }else{
    vdata.visible = false
  vdata.baseObject.agentNo = ''
   props.callbackFunc()
   }
}


defineExpose({
  show,
})
</script>

<style lang="less" scoped>
.rule{
  display: flex;
  align-items: center;
  gap: 20px;
  *{
    flex-shrink: 0;
  }
  &:nth-child(n + 2){
    margin-top: 10px;
  }
}
.cp{
  cursor: pointer;
}
.fz18{
  font-size: 18px;
}
</style>
